package com.neusoft.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.dto.CommentReq;
import com.neusoft.mapper.ArticlesMapper;
import com.neusoft.mapper.CommentMapper;
import com.neusoft.mapper.UsersMapper;
import com.neusoft.model.Articles;
import com.neusoft.model.Comments;
import com.neusoft.model.Users;
import com.neusoft.service.ICommentService;
import com.neusoft.utils.UserUtils;
import com.neusoft.vo.Author;
import com.neusoft.vo.CommentVo;
import com.neusoft.vo.MultiComments;
import com.neusoft.vo.SingleComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentService implements ICommentService {
    @Autowired
    ArticlesMapper articlesMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public MultiComments getCommentsByArticleSlug(String slug) {
        QueryWrapper<Articles> queryArticlesWrapper = new QueryWrapper<>();
        queryArticlesWrapper.eq("slug", slug);
        Articles articles = articlesMapper.selectOne(queryArticlesWrapper);
        Users currentUser = UserUtils.getLoginUser();
        List<CommentVo> comments;
        if (currentUser != null) {
            comments = commentMapper.getComments(articles.getId(), currentUser.getId());
        } else {
            comments = commentMapper.getComments(articles.getId(), 0);
        }
        MultiComments multiComments = new MultiComments();
        multiComments.setComments(comments);
        return multiComments;
    }

    @Override
    public SingleComment addComment(String slug, CommentReq commentReq) {
        QueryWrapper<Articles> queryArticlesWrapper = new QueryWrapper<>();
        queryArticlesWrapper.eq("slug", slug);
        Articles articles = articlesMapper.selectOne(queryArticlesWrapper);
        Comments comments = new Comments();
        comments.setBody(commentReq.getComment().getBody());
        comments.setArticleId(articles.getId());
        Users currentUser = UserUtils.getLoginUser();
        comments.setAuthorId(currentUser.getId());
        commentMapper.insert(comments);
        SingleComment singleComment = new SingleComment();
        CommentVo commentVo = commentMapper.getSingleComment(comments.getId(), currentUser.getId());

        System.out.println(commentVo.getAuthor());
        singleComment.setComment(commentVo);
        return singleComment;
    }
}
